package com.example.myapplication.ui.movie

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.android_program.data_class.movie_2_1
import com.example.myapplication.MovieDetailsActivity
import com.example.myapplication.R
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_movie_wellreceived.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.lang.reflect.Field
import kotlin.concurrent.thread

//热映
public class WellReceivedFragment() : Fragment() {

    val sever_ip = "192.168.43.8"
    val sever_ip2 = "192.168.31.197"
    val showAll_WellReceived_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_WellReceived.jsp"
    //val showAll_WellReceived_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_WellReceived.jsp"
    val Movielist1: ArrayList<movie_2_1> = ArrayList()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val root = inflater.inflate(R.layout.fragment_movie_wellreceived, container, false)

        return root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        Banner_initView_1()//轮播图
        Recycler_data_2()//列表数据加载
        Recycler_2_initView1()//列表初始化

    }
    /*轮播图开始*/
    private fun Banner_initView_1() {
        val arrayImageUrl1 = arrayListOf<Int>(R.drawable.p121, R.drawable.p122, R.drawable.p123)
        val arrayTitle1 = arrayListOf<String>("第一张", "第二张", "第三张")
        banner1.setBannerStyle(BannerConfig.NOT_INDICATOR)
        banner1.setImageLoader(MyLoader1())
        banner1.setImages(arrayImageUrl1)
        banner1.setBannerAnimation(Transformer.Default)
        banner1.setBannerTitles(arrayTitle1)
        banner1.setDelayTime(3000)
        banner1.isAutoPlay(true)
        banner1.setIndicatorGravity(BannerConfig.NOT_INDICATOR)
        banner1.setOnBannerListener {
            Log.d("=*=", "第几张" + it.dec())
            pagefuntion1(it.dec())
        }
        banner1.start()
    }
    private inner class MyLoader1 : ImageLoader() {
        override fun displayImage(context: Context, path: Any, imageView: ImageView) {
            Glide.with(context).load(path as Int).into(imageView)
        }
    }
    private fun pagefuntion1(page: Int) {
        var temp = page + 2
        /*if (temp == 1) {
            val intent = Intent(this, MainActivity1::class.java)
            startActivity(intent)
        } else if (temp == 2) {
            val intent = Intent(this, MainActivity2::class.java)
            startActivity(intent)
        } else if (temp == 3) {
            val intent = Intent(this, MainActivity3::class.java)
            startActivity(intent)
        }*/
    }
    /*轮播图结束*/

    /*列表开始*/
    private fun Recycler_2_initView1() {
        val layoutManager = LinearLayoutManager(context)
        myrecyclerview3.layoutManager = layoutManager
        val adapter3 = Movie2_1Aapter(Movielist1, this.requireContext())
        myrecyclerview3.adapter = adapter3
    }

    //列表数据加载
    fun Recycler_data_2() {
        //初始化数据
        getAllTrainInfoJson()

        /*Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人",
                "10.0",
                "无",
                "无"
            )
        )
        Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人2222",
                "10.0",
                "无",
                "无"
            )
        )
        Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人",
                "10.0",
                "无",
                "无"
            )
        )
        Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人",
                "10.0",
                "无",
                "无"
            )
        )
        Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人",
                "10.0",
                "无",
                "无"
            )
        )
        Movielist1.add(
            movie_2_1(
                R.drawable.movie_1,
                "疯狂原始人",
                "10.0",
                "无",
                "无"
            )
        )*/
    }
    private class Movie2_1ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var movie2_img1: ImageView = view.findViewById(R.id.movie2_img1)
        var movie2_name: TextView = view.findViewById(R.id.movie2_name)
        var movie2_score: TextView = view.findViewById(R.id.movie2_score)
        var movie2_actor: TextView = view.findViewById(R.id.movie2_actor)
        var movie_info: TextView = view.findViewById(R.id.movie_info)
        var movie2_info1: LinearLayout = view.findViewById(R.id.movie2_info1)
        var goupiao_3_1: ImageView = view.findViewById(R.id.goupiao_3_1)
    }
    //适配器
    private class Movie2_1Aapter(val Movielist1: List<movie_2_1>, val context: Context):
        RecyclerView.Adapter<Movie2_1ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):Movie2_1ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movie_2_1, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = Movie2_1ViewHolder(view)
            view.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = Movielist1[position]

                Toast.makeText(parent.context,"${info.movie2_name1}", Toast.LENGTH_LONG).show()

                val mIntent = Intent(context, MovieDetailsActivity::class.java)
                mIntent.putExtra("movie_name", info.movie2_name1)
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)
            }

            return viewHolder
        }
        override fun onBindViewHolder(holder: Movie2_1ViewHolder, position: Int) {
            val info = Movielist1[position]
            holder.movie2_img1.setImageResource(info.movie2_src1)
            holder.goupiao_3_1.setImageResource(R.drawable.p3)
            holder.movie2_name.text = info.movie2_name1
            holder.movie2_score.text = info.movie2_score1
            holder.movie2_actor.text = info.movie2_actor1
            holder.movie_info.text = info.movie2_info1
        }
        override fun getItemCount(): Int {
            return Movielist1.size
        }
    }
    /*列表结束*/

    //json解析
    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_WellReceived_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        // txtData.text = result

                        val layoutManager = LinearLayoutManager(context)
                        myrecyclerview3.layoutManager = layoutManager
                        val adapter3 = Movie2_1Aapter(Movielist1, this.requireContext())
                        myrecyclerview3.adapter = adapter3
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            Movielist1.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_name = jsonObject.getString("movie_name")
                val movie_src = jsonObject.getString("movie_src")
                val movie_score = jsonObject.getString("movie_score")
                val movie_actor = jsonObject.getString("movie_actor")
                val movie_info = jsonObject.getString("movie_info")

                //builder.append("$movie_name--$movie_src--$movie_score--$movie_kind, ")
                Movielist1.add(
                    movie_2_1(getResourceIdByString(movie_src), movie_name,
                        movie_score, movie_actor, movie_info)
                )
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}